//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace OpenLS.Spreadsheet.UI
{
    static class ImageSourceHelper
    {
        public static BitmapSource CleanImageSource(ImageSource source)
        {
            BmpBitmapEncoder ee = new BmpBitmapEncoder();
            BitmapSource src = (BitmapSource)source;
            ee.Frames.Add(BitmapFrame.Create(src));
            string fileName = Path.GetTempFileName();
             try
             {

                 using (Stream stream = File.Open(fileName, FileMode.OpenOrCreate))
                 {
                     ee.Save(stream);
                 }
                 using (Stream stream = File.Open(fileName, FileMode.OpenOrCreate))
                 {
                     BmpBitmapDecoder dec = new BmpBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat,
                                                                 BitmapCacheOption.OnLoad);
                     return dec.Frames[0];
                 }
             }
             finally
             {
                 File.Delete(fileName);
             }
        }
    }
}
